import { ref, computed, nextTick, onUnmounted, unref, type Ref } from "vue";
import * as echarts from "echarts";

// 使用示例
/**
 *
 *
<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useECharts } from "@/utils/useEchars"; // 导入你的 useECharts 钩子


// 创建一个 ref 引用，指向 ECharts 容器
const chartRef = ref<HTMLDivElement | null>(null);

// 使用 useECharts 钩子
const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

// 设置图表的选项
onMounted(() => {
  setOptions({
    title: {
      text: 'ECharts 示例',
      left: 'center',
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: [120, 200, 150, 80, 70, 110, 130],
        type: 'line',
      },
    ],
  });
});
</script>

<style scoped>
你可以自定义 ECharts 容器的样式
</style>
 *
 */

/**
 *
 * @param elRef
 * @returns
 */
export function useECharts(elRef: Ref<HTMLDivElement | null>) {
  const cacheOptions = ref({});
  let chartInstance: echarts.ECharts | null = null;

  function initCharts() {
    const el = unref(elRef);
    if (!el) return;

    chartInstance = echarts.init(el);
    window.addEventListener("resize", resize);
  }

  function setOptions(options: echarts.EChartsOption, clear = true) {
    cacheOptions.value = options;

    if (unref(elRef)?.offsetHeight === 0) {
      setTimeout(() => setOptions(unref(getOptions)), 30);
      return;
    }

    nextTick(() => {
      setTimeout(() => {
        if (!chartInstance) {
          initCharts();
          if (!chartInstance) return;
        }

        if (clear) chartInstance.clear();
        chartInstance.setOption(unref(getOptions));
      }, 30);
    });
  }

  function resize() {
    chartInstance?.resize();
  }

  const getOptions = computed((): echarts.EChartsOption => {
    return cacheOptions.value;
  });

  onUnmounted(() => {
    if (chartInstance) {
      window.removeEventListener("resize", resize);
      chartInstance.dispose();
      chartInstance = null;
    }
  });

  function getInstance(): echarts.ECharts | null {
    if (!chartInstance) {
      initCharts();
    }
    return chartInstance;
  }

  return {
    setOptions,
    resize,
    echarts,
    getInstance
  };
}
